package top.leyi.ServiceImpl;

import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import top.leyi.IService.ICourseService;
import top.leyi.entity.Course;
import top.leyi.mapper.CourseMappper;

import java.util.*;

/**
 * @author allen
 * @date 2019/5/11
 */

@Service("CourseService")
public class CourseServiceImpl implements ICourseService {
    @Autowired
    CourseMappper courseMappper;

    @Override
    public List<Course> getCourses(String classId, int week) {



        List<Integer> cs = courseMappper.queryCidByClassIdSort(classId);

        List<Course> courses = courseMappper.queryCoursesDetailsByCid(cs.get(0));

        List<Course> result = new ArrayList<>();
        for(Course course : courses){

            int from = Integer.parseInt(course.getQsz());
            int to = Integer.parseInt(course.getJsz());
            boolean isSingle = !course.getDsz().equals("双周");
            if(from <= week && to>= week && isSingle == (week%2!=0)){
                result.add(course);
            }

        }

        return result;
    }

    @Transactional
    @Override
    public void addCourse(Course course) {
        String id = "";
        id = courseMappper.ownerIsExist(course);
        if(id == null) {
            courseMappper.addOneCourse(course);
            id = courseMappper.queryCidByClassId(course.getClassId());
        }
        course.setCid(id);
        courseMappper.addOneCourseDetails(course);

    }

    /**
     * @descripe 按照json格式插入数据
     * @param course
     * @param data
     */

    @Override
    public void addCourses(Course course, JSONArray data) {
        String id = "";
        id = courseMappper.ownerIsExist(course);
        if(id == null) {
            courseMappper.addOneCourse(course);
            id = courseMappper.queryCidByClassId(course.getClassId());
        }
        //课程表id
        String cid = id;
        //课程表id
        String classId = course.getClassId();
        List<Course> courses = new ArrayList<>();


        //details课程表设置
        data.forEach((e)->{
            JSONObject ele = new JSONObject(e.toString());
            Course c = new Course();
            c.setCid(cid);
            c.setOwner(course.getOwner());
            c.setClassId(classId);
            Map  map = ele.toMap();

            c.setXqj(map.get("xqj").toString());
            c.setDjj(map.get("djj").toString());
            c.setDsz(map.get("dsz").toString());
            c.setQsz(map.get("qsz").toString());
            c.setJsz(map.get("jsz").toString());
            c.setTeacher(map.get("teacher").toString());
            c.setRoom(map.get("room").toString());
            c.setName(map.get("name").toString());

            courses.add(c);
            courseMappper.addOneCourseDetails(c);
        });
    }
}
